package com.daoshu.mti.kafkaclient.handle;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daoshu.mti.kafkaclient.bean.TKmGlkygpEntity;
import com.daoshu.mti.kafkaclient.bean.TKmJurisdictionEntity;
import com.daoshu.mti.kafkaclient.bean.TKmKyzEntity;
import com.daoshu.mti.kafkaclient.bean.TKmZdryYjEntity;
import com.daoshu.mti.kafkaclient.constant.Topic;
import com.daoshu.mti.kafkaclient.consumer.TKmTGlkygpBaseConsumer;
import com.daoshu.mti.kafkaclient.service.TKmGlkygpService;
import com.daoshu.mti.kafkaclient.service.TKmJurisdictionService;
import com.daoshu.mti.kafkaclient.service.TKmKyzService;
import com.daoshu.mti.kafkaclient.service.TKmZdryYjService;
import com.daoshu.mti.kafkaclient.utils.AddressOrLngLatConvertUtil;
import com.daoshu.mti.kafkaclient.utils.AddressResolutionUtil;
import com.daoshu.mti.kafkaclient.utils.ZdryYjUtilBean;
import com.daoshu.mti.kafkaclient.websocket.SocketType;
import com.daoshu.mti.kafkaclient.websocket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname TKmTldpHandle
 * @Description TODO
 * @Date 2020/1/17 21:15
 * @Created by duchaof
 * @Version 1.0
 */
@Slf4j
@Component
public class TKmGlkygpHandle extends TKmTGlkygpBaseConsumer {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private TKmGlkygpService tKmGlkygpService;
    @Autowired
    private TKmZdryYjService tKmZdryYjService;
    @Autowired
    private WebSocketUtils webSocketUtils;
    @Autowired
    private AddressOrLngLatConvertUtil addressUtil;
    @Autowired
    private TKmJurisdictionService tKmJurisdictionService;
    @Autowired
    private TKmKyzService tKmKyzService;

    private static Lock lock = new ReentrantLock();

    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void onDealMessage(String message)  {
        try {
            log.info("接收到topic："+ Topic.GLKYGP +"的消息"+",线程："+Thread.currentThread().getName()+"在"+sdf.format(new Date())+"开始处理接受到的消息："+message);
            TKmGlkygpEntity tKmGlkygpEntity = JSON.parseObject(message,TKmGlkygpEntity.class);
            Integer res = null;
            lock.lock();
            try {
                // 根据省份证号 预警时间判断是否为重复数据
                Boolean repeatFlag = tKmGlkygpService.judgeRepeatData(tKmGlkygpEntity);
                if (repeatFlag) {
                    return;
                }

                // 通过线路名称放入到起点站 和 终点站名称
                if (null != tKmGlkygpEntity.getXlmc() && tKmGlkygpEntity.getXlmc().length() > 0) {
                    String[] xl = null;
                    if (tKmGlkygpEntity.getXlmc().indexOf("->") >= 0) {
                        xl = tKmGlkygpEntity.getXlmc().split("->");
                    } else {
                        if (tKmGlkygpEntity.getXlmc().indexOf("-") >= 0) {
                            xl = tKmGlkygpEntity.getXlmc().split("-");
                        }
                    }
                    tKmGlkygpEntity.setQdzMc(xl[0]);
                    tKmGlkygpEntity.setZdzMc(xl[1]);
                }
                res = tKmGlkygpService.insert(tKmGlkygpEntity);
            }catch (Exception e){
               log.error("公路旅客预警数据入库时发生异常：========》",e.getMessage());
            } finally {
                lock.unlock();
            }
            if(res>0) {
                //log.info("数据插入成功，插入成功的数据为：" + message);
                TKmZdryYjEntity tKmZdryYjEntity = tKmGlkygpEntity.transtoZdryYjEntiy();

                if(tKmZdryYjEntity.getSendStation().indexOf("昆明")>=0){ // 起点站为昆明
                    TKmKyzEntity kyz = tKmKyzService.getKyzXxByGaId(tKmGlkygpEntity.getGaKyzid());
                    if(null != kyz){
                        tKmZdryYjEntity.setSendPro("云南");
                        if(null != kyz.getCity()&& kyz.getCity().length()>0) tKmZdryYjEntity.setSendCity(kyz.getCity());
                        tKmZdryYjEntity.setInOut(2);
                        if(null != kyz.getLng()&&kyz.getLng().length()>0)tKmZdryYjEntity.setSendLng(kyz.getLng());
                        if(null != kyz.getLat()&&kyz.getLat().length()>0)tKmZdryYjEntity.setSendLat(kyz.getLat());
                        if(null != kyz.getLng()&&kyz.getLng().length()>0)tKmZdryYjEntity.setX(kyz.getLng());
                        if(null != kyz.getLat()&&kyz.getLat().length()>0)tKmZdryYjEntity.setY(kyz.getLat());
                    }
                }else{
                    TKmKyzEntity kyz = tKmKyzService.getKyzXxByGaId(tKmGlkygpEntity.getGaKyzid()); //通过起点站名称来处理 未完待续
                    if(null != kyz) {
                        tKmZdryYjEntity.setSendLng(kyz.getLng());
                        tKmZdryYjEntity.setSendLat(kyz.getLat());
                        tKmZdryYjEntity.setSendPro("云南");
                        tKmZdryYjEntity.setSendCity(kyz.getCity());
                        if(kyz.getCity().equals("昆明")||kyz.getCity().equals("昆明市")){
                            tKmZdryYjEntity.setInOut(2);
                            tKmZdryYjEntity.setX(kyz.getLng());
                            tKmZdryYjEntity.setY(kyz.getLat());
                        }
                    }else {
                        Map<String, String> sendAddress = addressUtil.checkXY(tKmZdryYjEntity.getSendStation());
                        if (null != sendAddress) {
                            tKmZdryYjEntity.setSendLng(sendAddress.get("lng"));
                            tKmZdryYjEntity.setSendLat(sendAddress.get("lat"));
                            if (sendAddress.containsKey("search") && null != sendAddress.get("search")) {
                                Map<String, String> proCityMap = AddressResolutionUtil.addressResolution(sendAddress.get("search"));
                                tKmZdryYjEntity.setSendPro(AddressOrLngLatConvertUtil.InterceptProvince(proCityMap.get("province")));
                                tKmZdryYjEntity.setSendCity(AddressOrLngLatConvertUtil.InterceptCity(proCityMap.get("city")));
                                if (proCityMap.get("city").equals("昆明") || proCityMap.get("city").equals("昆明市")) {
                                    tKmZdryYjEntity.setInOut(2);
                                    tKmZdryYjEntity.setX(sendAddress.get("lng"));
                                    tKmZdryYjEntity.setY(sendAddress.get("lat"));
                                }
                            }
                        }
                    }
                }

                if(tKmZdryYjEntity.getEndname().indexOf("昆明")>=0){
                    TKmKyzEntity kyz = tKmKyzService.getKyzXxByXlmc(tKmGlkygpEntity.getXlmc());
                    if(null != kyz){
                        tKmZdryYjEntity.setEndPro("云南");
                        if(kyz.getCity().length()>0) tKmZdryYjEntity.setEndCity(kyz.getCity());
                        tKmZdryYjEntity.setInOut(1);
                        if(null != kyz.getLng()&&kyz.getLng().length()>0)tKmZdryYjEntity.setEndLng(kyz.getLng());
                        if(null != kyz.getLat()&&kyz.getLat().length()>0)tKmZdryYjEntity.setEndLat(kyz.getLat());
                        if(null != kyz.getLng()&&kyz.getLng().length()>0)tKmZdryYjEntity.setX(kyz.getLng());
                        if(null != kyz.getLat()&&kyz.getLat().length()>0)tKmZdryYjEntity.setY(kyz.getLat());
                    }
                }else{
                    Map<String,String> endAddress = addressUtil.checkXY(tKmZdryYjEntity.getEndname());
                    if(null != endAddress){
                        tKmZdryYjEntity.setEndLng(endAddress.get("lng"));
                        tKmZdryYjEntity.setEndLat(endAddress.get("lat"));
                        if(endAddress.containsKey("search") && null!= endAddress.get("search")){
                            Map<String,String> proCityMap = AddressResolutionUtil.addressResolution(endAddress.get("search"));
                            tKmZdryYjEntity.setEndPro(AddressOrLngLatConvertUtil.InterceptProvince(proCityMap.get("province")));
                            tKmZdryYjEntity.setEndCity(AddressOrLngLatConvertUtil.InterceptCity(proCityMap.get("city")));
                            if((proCityMap.get("city").equals("昆明")||proCityMap.get("city").equals("昆明市")) && tKmZdryYjEntity.getSendStation().indexOf("昆明")<0){
                                tKmZdryYjEntity.setInOut(1);
                                tKmZdryYjEntity.setX(endAddress.get("lng"));
                                tKmZdryYjEntity.setY(endAddress.get("lat"));
                            }
                        }
                    }
                }
                // 查询预警发生地的派出所代码和名称
                TKmJurisdictionEntity tKmJurisdictionEntity = tKmJurisdictionService.queryYjdPcsByLngAndLat(tKmZdryYjEntity.getX(),tKmZdryYjEntity.getY());
                if(null != tKmJurisdictionEntity) {
                    tKmZdryYjEntity.setYjdPcs(tKmJurisdictionEntity.getMc());
                    tKmZdryYjEntity.setYjdPcsCode(String.format("%.0f",Double.parseDouble(tKmJurisdictionEntity.getDm())));
                    tKmZdryYjEntity.setYjdSsfj(tKmJurisdictionEntity.getSsfj());
                }
                tKmZdryYjService.insert(tKmZdryYjEntity);
                ZdryYjUtilBean zdryYjUtilBean = tKmGlkygpEntity.transtoZdryYjUtilBean();
                zdryYjUtilBean.setYjwybs(tKmZdryYjEntity.getWybs());
                if(null != tKmJurisdictionEntity){
                    StringBuilder sb = new StringBuilder("重点人员【");
                    sb.append(zdryYjUtilBean.getName()).append("】在").append(tKmJurisdictionEntity.getMc())
                            .append("的管辖范围内乘坐客运大巴");
                    if(tKmZdryYjEntity.getInOut()==1){
                        sb.append("到达昆明。");
                    }else if(tKmZdryYjEntity.getInOut()==2){
                        sb.append("离开昆明。");
                    }else
                    {
                        sb.append("。");
                    }
                    zdryYjUtilBean.setYjMsg(sb.toString());
                }
                if(null!=tKmGlkygpEntity.getZjhm()) {
                    List<String> tokens = tKmZdryYjService.findWebsocketPsuhUserListBySfzh(tKmGlkygpEntity.getZjhm());
                    //查询此条预警是否是灰名单 或者是 已稳控  如果是就不推送
                    TKmZdryYjEntity entity = tKmZdryYjService.authGkjbAndWkzt(tKmGlkygpEntity.getZjhm());
                    if (!ObjectUtils.isEmpty(entity)) {
                        return;
                    }
                    if(null != tokens) {
                        webSocketUtils.sendWebsockMessageToUser(tokens,
                                Arrays.asList("glky-gp", JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getCode());
                    }
                  }
            }else {
                log.error("数据插入失败，插入失败的数据为："+message);
            }
        } catch (Exception e) {
           log.error("插入数据库发生异常=====>{}",e.getMessage());
        }
    }

}
